#include "Mutex.hpp"

using namespace MutexMoble;

int ticket = 1000;


class ThreadData
{
public:
    ThreadData(Mutex *lock, const char *name) // 直接传引用，嘎嘎好用
        : _lock(lock),
          _name(name)
    {
    }
    ~ThreadData() {}  //析构函数虽然在此时没啥用，但还是写了把，写了总比不写好
    Mutex* _lock;
    std ::string _name;
};

void* Ticket(void* argc)
{
    ThreadData* s1 = static_cast<ThreadData*>(argc);
    while(1)
    {
        LockGuard a1(*s1->_lock);
        if(ticket > 0)
        {
            usleep(1000);
            printf("%s 正在抢票，此时的票数剩余：%d\n",s1->_name.c_str(),ticket--);
        }
        else
        {
            break;
        }
    }
    return nullptr;
}



int main()
{
    Mutex s1;
    pthread_t a1,a2,a3,a4; // 创建一个线程来让它完成抢票系统
    ThreadData* t1 = new ThreadData(&s1,"thread -1");   //一定要自己创造出一个变量，因为这是堆，只有在最后的时候才会左清楚，如果是栈的话资源可能会被挤掉
    pthread_create(&a1, nullptr, Ticket, t1);   
    ThreadData* t2 = new ThreadData(&s1,"thread -2");
    pthread_create(&a2, nullptr, Ticket, t2);
    ThreadData* t3 = new ThreadData(&s1,"thread -3");
    pthread_create(&a3, nullptr, Ticket, t3);
    ThreadData* t4 = new ThreadData(&s1,"thread -4");
    pthread_create(&a4, nullptr, Ticket, t4);

    pthread_join(a1,nullptr); //进行线程等待
    pthread_join(a2,nullptr); //进行线程等待
    pthread_join(a3,nullptr); //进行线程等待
    pthread_join(a4,nullptr); //进行线程等待
    delete t1;
    delete t2;
    delete t3;
    delete t4;
    return 0;
}